/*
 * @Description:
 * @Author: Junhuang
 * @Date: 2022-02-15 16:56:55
 * @LastEditTime: 2022-05-23 14:25:59
 * @LastEditors: Junhuang
 * @Reference:
 */
'use strict';

const Controller = require('egg').Controller;

// 参数校验规则
const rules = {
  no: { type: 'number', required: true, desc: '集号' },
  title: { type: 'string', required: true, desc: '视频标题' },
  url: { type: 'string', required: true, desc: '视频地址' },
  video_id: { type: 'int', required: true, desc: '作品ID' },
  description: { type: 'string', required: false, desc: '描述' },
};

class Video_detailController extends Controller {

  async index() {
    const { ctx, app } = this;
    // 参数验证
    ctx.validate({
      video_id: {
        required: true,
        type: 'int',
        desc: '作品id',
      },
    });

    const video_id = ctx.query.video_id;
    const res = await app.model.VideoDetail.findAll({
      where: {
        video_id,
      },
      order: [[ 'no', 'ASC' ]],
      // 增加字段video,让其值=url，因为前台需要
      attributes: { include: [[ 'url', 'video' ]] },
    });

    ctx.apiSuccesss(res);
  }

  async save() {
    const { ctx, app } = this;
    const { no, title, video_id, url, description } = ctx.request.body;
    // 参数验证
    ctx.validate(rules);
    const user_id = ctx.authUser.id;

    // 先需要通过video_id 和 user_id 查询数据库中是否有属于此用户的这个作品
    const video = await app.model.Video.findOne({
      where: {
        id: video_id,
        user_id,
      },
    });
    if (!video) {
      ctx.throw(404, '所属作品不存在');
    }
    // 【特别注意】：VideoDetail的驼峰式写法
    const video_detail = await app.model.VideoDetail.create({
      no, title, url, video_id, description,
    });

    ctx.apiSuccesss(video_detail);
  }

  // 修改视频
  async update() {
    const { ctx, app } = this;
    const { no, title, video_id, url, description } = ctx.request.body;
    const id = ctx.params.id;
    // 参数验证
    ctx.validate({
      id: {
        type: 'int', required: true, desc: '视频id',
      },
      ...rules,
    });
    const user_id = ctx.authUser.id;

    // 先需要通过video_id 和 user_id 查询数据库中是否有属于此用户的这个作品
    const video = await app.model.Video.findOne({
      where: {
        id: video_id,
        user_id,
      },
    });
    if (!video) {
      ctx.throw(404, '所属作品不存在');
    }
    // 【特别注意】：注意VideoDetail的驼峰式写法
    const vd = await app.model.VideoDetail.findOne({
      where: {
        id,
        video_id,
      },
    });

    if (!vd) {
      ctx.throw(404, '该视频不存在');
    }

    const rs = await vd.update({
      no, title, url, video_id, description,
    });

    ctx.apiSuccesss(rs);
  }

  // 删除
  async destroy() {
    const { ctx, app } = this;
    const { id } = ctx.request.body;
    const currentUser = ctx.authUser;
    ctx.validate({
      id: {
        type: 'int', required: true, desc: '视频id',
      },
    });
    // 注意VideoDetail的驼峰式写法
    // 【特别注意】：此处的关联查询，不仅该视频要存在，且该视频所属的作品要是该用户的才行
    const vd = await app.model.VideoDetail.findOne({
      where: {
        id,
      },
      include: [{
        model: app.model.Video,
        where: {
          user_id: currentUser.id,
        },
      }],
    });

    if (!vd) {
      return ctx.throw('该记录不存在或该记录不属于当前用户');
    }

    const res = await vd.destroy();
    ctx.apiSuccesss(res);
  }

  // 后台查询视频列表分页
  // video_detail_list_page
  async list() {
    const { ctx, app } = this;
    const where = {};
    const video_where = {}; // 作品查询条件
    const user_where = {}; // 用户查询条件
    const Op = app.Sequelize.Op;

    // 组织查询条件
    // id用全等
    if (ctx.query.id && ctx.query.id.length > 0) {
      where.id = ctx.query.id;
    }

    // no用全等
    if (ctx.query.no && ctx.query.no.length > 0) {
      where.no = ctx.query.no;
    }
    // stauts全等
    if (ctx.query.status) {
      where.status = parseInt(ctx.query.status);
    }

    // category_id全等
    if (ctx.query.category_id) {
      video_where.category_id = parseInt(ctx.query.category_id);
    }

    // title用like
    if (ctx.query.title && ctx.query.title.length > 0) {
      where.title = {
        [Op.like]: '%' + ctx.query.title + '%',
      };
    }

    // vtitle用like
    if (ctx.query.vtitle && ctx.query.vtitle.length > 0) {
      video_where.title = {
        [Op.like]: '%' + ctx.query.vtitle + '%',
      };
    }

    // nickname用like
    if (ctx.query.nickname && ctx.query.nickname.length > 0) {
      user_where.nickname = {
        [Op.like]: '%' + ctx.query.nickname + '%',
      };
    }

    const options = {
      include: [{
        model: app.model.Video,
        attributes: [ 'id', 'title', 'cover', 'description' ],
        where: video_where,
        include: [{
          model: app.model.Category,
          attributes: [ 'id', 'title', 'cover', 'description' ],
        }, {
          model: app.model.User,
          attributes: [ 'id', 'username', 'nickname', 'avatar' ],
          where: user_where,
        }],
      }],
      order: [[ 'video', 'category_id' ], [ 'video', 'user', 'id', 'ASC' ], [ 'video', 'id' ], [ 'no', 'ASC' ]],
    };

    const res = await ctx.pageAndCount(app.model.VideoDetail, where, options);
    const items = [];
    res.rows.forEach(el => {
      const item = JSON.parse(JSON.stringify(el));
      if (el.video) {
        item.video_title = el.video.title;
        item.video_cover = el.video.cover;
        if (el.video.category) {
          item.category_id = el.video.category.category_id;
          item.category_title = el.video.category.title;
        }
        if (el.video.user) {
          item.user_nickname = el.video.user.nickname;
          item.user_username = el.video.user.username;
          item.user_id = el.video.user.id;
          item.user_avatar = el.video.user.avatar;
        }
        delete item.video;
      }
      items.push(item);
    });
    ctx.apiSuccesss({
      total: res.count,
      items,
    });
  }

  // 更改视频状态
  // '/video_detail/:id/status'
  async changeStatus() {
    const { ctx, app } = this;
    let { status } = ctx.request.body;
    status = parseInt(status);
    ctx.validate({
      id: {
        required: true,
        type: 'int',
        desc: 'id',
      },
      status: {
        required: true,
        type: 'int',
        desc: 'status',
      },
    });

    const vd = await app.model.VideoDetail.findOne({
      where: {
        id: ctx.params.id,
      },
    });

    if (!vd) {
      return ctx.throw(404, '该视频不存在');
    }

    if (vd.status === status) {
      return ctx.throw('该视频状态与要变化的状态一致，不用变化！');
    }

    vd.status = status;
    vd.save();

    const res = JSON.parse(JSON.stringify(vd));
    return ctx.apiSuccesss(res);
  }
}

module.exports = Video_detailController;
